from celery import Celery
import sys
import os

from django.core.mail import send_mail

from django.conf import settings
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE_DIR, 'meiduo_mall'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'meiduo_mall.dev'

# 定义celery实例，参数：１．实例名　　２．　任务发布位置　　３．结果保存位置
app = Celery('meiduo', broker='redis://127.0.0.1:6379/14', backend='redis://127.0.0.1/15')


@app.task(bind=True,name='send_sms_code')
def send_sms_code(self, mobile, sms_code):
    from libs.yuntongxun.sms import CCP

    try:
        ccp = CCP()
        res = ccp.send_template_sms(mobile, [sms_code, 5], 1)
    except:
        res = -1

    if res == -1:
        self.retry(countdown=5, max_retries=3, exc=Exception('短信发送失败'))


@app.task(bind=True, name='send_verify_email', retry_backoff=3)
def send_verify_email(self, subject, to_email, verify_url):

    message = '''
     <p>点击链接认证邮箱</p>
     <p><a href="%s">认证邮箱</a></p>
    ''' % verify_url
    print('verify email')
    try:
        send_mail(subject, '', settings.EMAIL_FROM, [to_email], html_message=message)
        print('send email success')

    except Exception as e:
        raise self.retry(countdown=5, max_retries=3, exc=e)


